package com.zygh.lz.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.dao.SectionMapper;
import com.zygh.lz.dao.SignMapper;
import com.zygh.lz.dao.StaffMapper;
import com.zygh.lz.dao.XareaMapper;
import com.zygh.lz.entity.*;
import com.zygh.lz.entity.bean.OnLine;
import com.zygh.lz.entity.changfeng.SignIn;
import com.zygh.lz.service.SignService;
import com.zygh.lz.service.impl.LongFengService;
import com.zygh.lz.stapprove.*;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Api(tags = "APP签到签退模块", description = "SignController")
@RestController
public class AppSignController {


    @Resource
    private SignService signService;
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private XareaMapper xareaMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private SignMapper signMapper;
    @Resource
    private LongFengService longFengService;


    @ApiOperation("签到接口")
    @PostMapping("signqd")
    @ViLog(logType = "1", module = "APP签到接口")
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public OutBean signqd(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        Sign sign = new Sign();
        sign.setSignnum(jsonObject.getString("signNum"));
        sign.setAssignmentname(jsonObject.getString("assignmentname"));
        sign.setGpsx(jsonObject.getString("gpsx"));
        sign.setGpsy(jsonObject.getString("gpsy"));
        sign.setStaffid(Integer.valueOf(jsonObject.getString("staffid")));
        sign.setStaffname(jsonObject.getString("staffname"));
        sign.setSectionname(jsonObject.getString("sectionname"));
        sign.setSectionid(jsonObject.getString("sectionid"));
        sign.setSignintime(jsonObject.getString("signintime"));
        sign.setSignouttime(jsonObject.getString("signouttime"));
        sign.setComment(jsonObject.getString("comment"));
        sign.setWarningsignal(jsonObject.getString("warningsignal"));
        sign.setAssignmentid(Integer.parseInt(jsonObject.getString("assignmentid")));
        sign.setGpsqtx(jsonObject.getString("gpsqtx"));
        sign.setGpsqty(jsonObject.getString("gpsqty"));
        if (StringUtils.isNotEmpty(jsonObject.getString("taskId"))) {
            sign.setRwid(jsonObject.getString("taskId"));  //市局特殊勤务任务id
        }
        sign.setState(Integer.valueOf(jsonObject.getString("state")));
        log.info("签到请求：" + sign.getStaffid());

        try {
            ResultBeans resultBeans = signService.signqd(sign);
            return OutBeanUtil.resSuc(resultBeans, inBean);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("【 Ali pay 异常 】", e);
        }
        return OutBeanUtil.resSuc(null, inBean);
    }

    /**
     * 签到给长峰科技推送
     */
    private String CFqdpush(Sign sign) {
        Staff staff = staffMapper.selectByPrimaryKey(sign.getStaffid());
        Section section = sectionMapper.selectByPrimaryKey(staff.getSysSectionId());
        Xarea xarea = xareaMapper.selectByPrimaryKey(sign.getAssignmentid());
        String rwid = xarea.getRwid();
        //String rwid = sectionMapper.getRwid(staff.getStaffNum());

        if (StringUtils.isEmpty(rwid)) {
            log.error("无任务id民警：" + staff.getStaffNum());
        }
        SignIn signIn = new SignIn();

        signIn.setPhone(staff.getStaffIdcard())
                .setUserid(staff.getStaffNum())
                .setUsername(staff.getStaffName())
                .setZw(staff.getStaffPost())
                .setZzjgdm(section.getTempid())
                .setQdlat(sign.getGpsx())
                .setQdlng(sign.getGpsy())
                .setRwid(rwid);

        return longFengService.sendSignIn(signIn);
    }

    @ApiOperation("签退接口")
    @PostMapping("sifnqt")
    @ViLog(logType = "1", module = "APP签退接口")
    public OutBean sifnqt(Sign sign, @RequestBody(required = false) InBean inBean) {

        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        sign.setComment(jsonObject.getString("comment"));
        sign.setWarningsignal(jsonObject.getString("warningsignal"));
        sign.setAssignmentid(Integer.valueOf(jsonObject.getString("assignmentid")));
        sign.setGpsqtx(jsonObject.getString("gpsqtx"));
        sign.setGpsqty(jsonObject.getString("gpsqty"));
        sign.setState(2);

        ResultBeans resultBeans = signService.sifnqt(sign);

        return OutBeanUtil.resSuc(resultBeans, inBean);
    }

    @ApiOperation("app获取特殊勤务任务组树")
    @PostMapping("getTaskGroupTree")
    @ViLog(logType = "1", module = "app获取特殊勤务任务组树")
    public OutBean getTaskGroupTree(@RequestBody(required = false) InBean inBean) {
        ResultBeans resultBeans = longFengService.getTaskGroupTree();
        return OutBeanUtil.resSuc(resultBeans, inBean);
    }

    @ApiOperation("根据任务组id查询任务信息")
    @PostMapping(value = "findDutyMessag")
    public OutBean findDutyMessag(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        DutyMessag dutyMessag = new DutyMessag();
        dutyMessag.setIfValid(Integer.valueOf(jsonObject.getString("ifValid")));
        dutyMessag.setTaskgroupIds(new String[]{jsonObject.getString("taskgroupIds")});
        dutyMessag.setSerTaskInfoUnitList(new String[]{jsonObject.getString("serTaskInfoUnitList")});
        ResultBeans resultBeans = longFengService.findDutyMessag(dutyMessag);
        return OutBeanUtil.resSuc(resultBeans, inBean);
    }

    @ApiOperation("任务签到装备绑定接口")
    @PostMapping("signWithEmt")
    public OutBean signWithEmt(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        SignWithEmt signWithEmt = new SignWithEmt();
        signWithEmt.setQdid(jsonObject.getString("qdid"));   //签到id
        signWithEmt.setZbids(new String[]{jsonObject.getString("zbids")});   //装备id集合
        ResultBeans resultBeans = longFengService.signWithEmt(signWithEmt);
        return OutBeanUtil.resSuc(resultBeans, inBean);
    }


    @ApiOperation("查询在线人信息")
    @RequestMapping(value = "findOnlineUser", method = RequestMethod.GET)
    public List<HashMap> findOnlineUser(String battalion) {
        return signService.findOnlineUser(battalion);
    }


    @ApiOperation("查询昨日在线警力详情")
    @ApiImplicitParam(name = "battalion", value = "大队名称", dataType = "String")
    @GetMapping("yesterdayData")
    public ResultBean yesterdayData(String battalion) {
        List<HashMap> hashMaps = signService.yesterdayData(battalion);
        return ResultUtil.setOK("success", hashMaps);
    }

    @ApiOperation("签到签退列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "warningsignal", value = "警号", dataType = "String", required = true),
            @ApiImplicitParam(name = "starttime", value = "签到时间", dataType = "string", required = true),
            @ApiImplicitParam(name = "endtime", value = "签退时间", dataType = "string", required = true),
            @ApiImplicitParam(name = "sectionid", value = "大队id", dataType = "string", required = true)})
    @GetMapping("findSignList")
    public ResultBean findSignList(String warningsignal, String starttime, String endtime, String sectionId,
                                   @RequestParam(defaultValue = "1") int pageNum,
                                   @RequestParam(defaultValue = "15") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Sign> signList = signService.findSignList(warningsignal, starttime, endtime, sectionId);
        PageInfo<Sign> pageInfo = new PageInfo<Sign>(signList);
        return ResultUtil.setOK("success", pageInfo);
    }

    @ApiOperation("APP车牌识别算法")
    @PostMapping("/signCount")
    public OutBean getCount(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        String picture = jsonObject.getString("picture");
//        net.sf.json.JSONArray dataJson = net.sf.json.JSONArray.fromObject(picture);
//        List<String> list = (List<String>) JSONArray.toCollection(dataJson, String.class);
        ResultBeans resultBeans = signService.personSign(picture);
        return OutBeanUtil.resSuc(resultBeans, inBean);
    }


    /**
     * 个人签到统计查询
     *
     * @param staffId 警号
     * @return ResultBean
     */
    @ApiOperation("个人签到统计查询详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "staffId", value = "警号", dataType = "Integer", required = true)})
    @PostMapping("/signCountDetail")
    public ResultBean getCountDetail(Integer staffId, String startDate, String endDate) {
        return signService.personSignDetail(staffId, startDate, endDate);
    }

    /**
     * 个人签到统计查询按月查询
     *
     * @param staffId 警号
     * @return ResultBean
     */
    @ApiOperation("个人签到统计查询按月查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "staffId", value = "警号", dataType = "Integer", required = true)})
    @PostMapping("/signCountDetailByMonth")
    public ResultBean getCountDetailByMonth(Integer staffId, String date) {
        return signService.personSignDetailByMonth(staffId, date);
    }

    /**
     * 签到月报
     *
     * @param staffId   警员id
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return ResultBean
     */
    @ApiOperation("个人签到月报")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "staffId", value = "警号", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", required = true),
                    @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", required = true)
            })
    @PostMapping("/signDetial")
    public ResultBean getMonth(Integer staffId, String startDate, String endDate) {
        return signService.personMonth(staffId, startDate, endDate);
    }


    @ApiOperation("个人签到月报")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "staffId", value = "警号", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "date", value = "日期", dataType = "String", required = true)
            })
    @PostMapping("/signDetialMonth")
    public OutBean getDetialMonth(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        ResultBeans resultBean = signService.detialMonth(Integer.valueOf(jsonObject.getString("staffId")), jsonObject.getString("date"));
        return OutBeanUtil.resSuc(resultBean, inBean);
    }

    @ApiOperation("APP个人签到详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staffId", value = "警号", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "date", value = "时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "current", value = "页码", dataType = "Integer", required = true, paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "Integer", required = true, paramType = "query")
    })
    @PostMapping("/detail")
    public ResultBean getDetail(Integer staffId, String date,
                                @RequestParam(name = "current", defaultValue = "1") Integer current,
                                @RequestParam(name = "size", defaultValue = "10") Integer size) {
        return signService.signDetail(staffId, date, current, size);
    }


    /**
     * ===========================================================
     * 当班在线警力
     *
     * @return ResultBean
     */
    @ApiModelProperty("当班在线警力")
    @PostMapping("onDutyOnLine")
    public ResultBean onDutyOnLine(@RequestBody OnLine onLine) {

        List<Map<String, Object>> maps = signService.onDutyOnLine(onLine.getOnLine());
        return ResultUtil.setOK("success", maps);

    }

    @ApiOperation("查询昨日在线警力")
    @ApiImplicitParam(name = "battalion", value = "大队名称", dataType = "String")
    @GetMapping("onlineYesterday")
    public ResultBean onlineYesterday(String battalion) {
        int yesterday = signService.onlineYesterday(battalion);
        return ResultUtil.setOK("success", yesterday);
    }

    @ApiModelProperty("昨日在线警力详情")
    @GetMapping("yesterdayOnLine")
    public ResultBean yesterdayOnLine(String battalion) {
        List<Map> maps = signService.yesterdayOnLine(battalion);
        return ResultUtil.setOK("success", maps);

    }

    @ApiModelProperty("昨日在线警力签到岗位详情")
    @GetMapping("yesterdaySignStation")
    public ResultBean yesterdaySignStation(String staffid, String shiftop) {
        List<Map> maps = signService.yesterdaySignStation(staffid, shiftop);
        return ResultUtil.setOK("success", maps);

    }

    /**
     * 签到数=正常签到数（高峰岗大于30分钟，其他大于2小时，包含迟到早退的签到；只要达到时长都算签到数）
     * ======================================签到统计====================================================
     */


    @ApiModelProperty("签到统计签到数，迟到，早退，漏签数")
    @GetMapping("signInStatistics")
    public ResultBean signInStatistics(Integer sectionId, String startTime, String endTime, Integer shiftop) {
        Map maps = signService.signInStatistics(sectionId, startTime, endTime, shiftop);
        return ResultUtil.setOK("success", maps);
    }

    @ApiModelProperty("支队层面按照班次签到数统计")
    @GetMapping("signInDetail")
    public ResultBean signInDetail(Integer sectionId, String startTime, String endTime, Integer shiftop) {
        List<Map> maps = signService.signInDetail(sectionId, startTime, endTime, shiftop);
        return ResultUtil.setOK("success", maps);
    }

    @GetMapping("/sign/in/detail")
    public ResultBean signInDetail2(HttpServletRequest request, Integer sectionId, String startTime, String endTime, Integer shiftop) {
        List<Map> maps = signService.signInDetail2(request, sectionId, startTime, endTime, shiftop);
        return ResultUtil.setOK("success", maps);
    }

    @ApiModelProperty("大队层面按照班次签到数统计")
    @GetMapping("signInDetailByLochus")
    public ResultBean signInDetailByLochus(Integer sectionId, String startTime, String endTime, Integer shiftop) {
        List<Map> maps = signService.signInDetailByLochus(sectionId, startTime, endTime, shiftop);
        return ResultUtil.setOK("success", maps);
    }

    @ApiModelProperty("大队层面按照班次签到统计详情")
    @GetMapping("signInByLochus")
    public ResultBean signInByLochus(Integer sectionDId, Integer sectionId, String startTime, String endTime, Integer shiftop) {
        List<Map<String, Object>> maps = signService.signInByLochus(sectionDId, sectionId, startTime, endTime, shiftop);
        return ResultUtil.setOK("success", maps);
    }


    @ApiModelProperty("支队层面按照岗位签到数统计")
    @GetMapping("SignDetailByStation")
    public ResultBean SignDetailByStation(Integer sectionId, String startTime, String endTime) {
        List<Map> maps = signService.SignDetailByStation(sectionId, startTime, endTime);
        return ResultUtil.setOK("success", maps);
    }

    @ApiModelProperty("大队层面按照岗位签到数统计")
    @GetMapping("SignDetailByStationLochus")
    public ResultBean SignDetailByStationLochus(Integer sectionId, String startTime, String endTime, String station) {
        List<Map> maps = signService.SignDetailByStationLochus(sectionId, startTime, endTime, station);
        return ResultUtil.setOK("success", maps);
    }

    @ApiModelProperty("大队层面按照岗位签到统计详情")
    @GetMapping("SignByStationLochus")
    public ResultBean SignByStationLochus(Integer sectionDId, Integer sectionId, String startTime, String endTime, String station) {
        List<Map<String, Object>> maps = signService.SignByStationLochus(sectionDId, sectionId, startTime, endTime, station);
        return ResultUtil.setOK("success", maps);
    }


    @ApiModelProperty("支队层面按照班次签到统计详情")
    @GetMapping("SignInStatistics")
    public ResultBean SignInStatistics(Integer sectionId, String startTime, String endTime, Integer shiftop) {
        List<Map<String, Object>> maps = signService.SignInStatistics(sectionId, startTime, endTime, shiftop);
        return ResultUtil.setOK("success", maps);
    }


    @ApiModelProperty("支队层面按照岗位签到统计详情")
    @GetMapping("SignInStationByDetail")
    public ResultBean SignInStationByDetail(Integer sectionId, String startTime, String endTime, String station) {
        List<Map<String, Object>> maps = signService.SignInStationByDetail(sectionId, startTime, endTime, station);
        return ResultUtil.setOK("success", maps);
    }


    @ApiModelProperty("支队层级统计导出按日")
    @GetMapping("StatisticsExport")
    public String StatisticsExport(HttpServletResponse response, Integer sectionDId, String startTime, String endTime) throws IOException, ParseException {
        return signService.StatisticsExport(response, sectionDId, startTime, endTime);
    }

    @ApiModelProperty("支队层级统计导出按周，按月")
    @GetMapping("StatisticsExportByWeek")
    @SysPcLog(module = "支队层级统计导出按周，按月", operation = "导出")
    public String StatisticsExportByWeek(HttpServletResponse response, Integer sectionId, String startTime, String endTime) throws IOException, ParseException {
        if (Objects.nonNull(sectionId)) {
            signService.generalSection(response, sectionId, startTime, endTime);
            return "success";
        }
        return signService.StatisticsExportByWeek(response, sectionId, startTime, endTime);
    }


    @ApiModelProperty("数据统计详情导出")
    @GetMapping("SignInExport")
    @SysPcLog(module = "数据统计详情导出", operation = "导出")
    public String SignInExport(HttpServletResponse response, Integer sectionId, String startTime, String endTime, Integer shiftop) throws IOException, ParseException {
        return signService.SignInExports(response, sectionId, startTime, endTime, shiftop);
    }

    @ApiModelProperty("大队层级签到统计导出")
    @GetMapping("SignInExportLochus")
    public String SignInExportLochus(HttpServletResponse response, Integer sectionDId, Integer sectionId, String startTime, String endTime, String station) throws IOException, ParseException {
        return signService.SignInExportLochus(response, sectionDId, sectionId, startTime, endTime, station);
    }


    /**
     * ======================================签到统计end====================================================
     */


    @ApiModelProperty("可视化界面当日数据统计，在线数、巡查里程")
    @GetMapping("signInNum")
    public ResultBean signInNum(Integer sectionId, String time, HttpServletRequest request) {
        return ResultUtil.setOK("success", signService.signInNum(sectionId, time, request));
    }

    @ApiModelProperty("可视化界面，签到按天统计各大队签到人次")
    @GetMapping("signInNumBySection")
    public ResultBean signInNumBySection(Integer sectionId, String time) {
        return ResultUtil.setOK("success", signService.signInNumBySection(sectionId, time, 0));
    }

    @ApiModelProperty("可视化界面，签到按天统计各大队下中队签到人次")
    @GetMapping("signInNumByLochus")
    public ResultBean signInNumByLochus(Integer sectionId, String time) {
        return ResultUtil.setOK("success", signService.signInNumByLochus(sectionId, time, 0));
    }


    @ApiModelProperty("可视化界面，签到按天统计各大队巡查里程排名")
    @GetMapping("distanceRanking")
    public ResultBean distanceRanking(Integer sectionId, String time) {
        return ResultUtil.setOK("success", signService.distanceRanking(sectionId, time, 0));
    }


    @ApiModelProperty("可视化界面，签到按天统计各中队巡查里程排名")
    @GetMapping("distanceRankingLochus")
    public ResultBean distanceRankingLochus(Integer sectionId, String time) {
        return ResultUtil.setOK("success", signService.distanceRankingLochus(sectionId, time, 0));
    }


    @ApiModelProperty("可视化界面，巡查总里程人员排名")
    @GetMapping("findMileageBySection")
    public ResultBean findMileageBySection(Integer sectionId, String time, String staffname) {
        return ResultUtil.setOK("success", signService.findMileageBySection(sectionId, time, staffname));
    }

    @ApiModelProperty("可视化界面，签到按天统计各中队人员巡查里程情况")
    @GetMapping("findMileageByLochus")
    public ResultBean findMileageByLochus(Integer sectionId, String time, String staffname) {
        return ResultUtil.setOK("success", signService.findMileageByLochus(sectionId, time, staffname));
    }


    @ApiModelProperty("可视化界面，大队层本周在线数和上周签到数作对比")
    @GetMapping("SignInComparison")
    public ResultBean SignInComparison(Integer sectionId) throws ParseException {
        return ResultUtil.setOK("success", signService.SignInComparison(sectionId));
    }

    @ApiModelProperty("可视化界面，中队本周在线数和上周签到数作对比")
    @GetMapping("SignInComparisonLochus")
    public ResultBean SignInComparisonLochus(Integer sectionId) throws ParseException {
        return ResultUtil.setOK("success", signService.SignInComparisonLochus(sectionId));
    }


    @ApiModelProperty("可视化界面，中队本周里程数和上周里程数作对比")
    @GetMapping("mileageBrokenLine")
    public ResultBean mileageBrokenLine(Integer sectionId) throws ParseException {
        return ResultUtil.setOK("success", signService.mileageBrokenLine(sectionId));
    }


    @ApiModelProperty("可视化界面，中队本周里程数和上周里程数作对比")
    @GetMapping("mileageBrokenLineLochus")
    public ResultBean mileageBrokenLineLochus(Integer sectionId) throws ParseException {
        return ResultUtil.setOK("success", signService.mileageBrokenLineLochus(sectionId));
    }


    @ApiModelProperty("可视化界面，查人的巡查轨迹")
    @GetMapping("findTrackByStaffId")
    public ResultBean findTrackByStaffId(Integer staffId, String time) {
        return ResultUtil.setOK("success", signService.findTrackByStaffId(staffId, time));
    }

    @ApiModelProperty("数据详情统计")
    @GetMapping("Statistics")
    public void Statistics(String startDay, String endDay) {
        signService.Statistics(startDay, endDay);
    }

    @ApiModelProperty("数据统计")
    @GetMapping("General")
    public void General(String startDay, String endDay) {
        signService.General(startDay, endDay);
    }


}

